package com.mutouren.modules.organize.service.impl;

import java.util.List;

import com.mutouren.common.entity.ValidState;
import com.mutouren.modules.organize.dao.FunctionDao;
import com.mutouren.modules.organize.dao.OrgDaoManager;
import com.mutouren.modules.organize.model.Function;
import com.mutouren.modules.organize.service.FunctionService;

public class FunctionServiceImpl implements FunctionService {

	private static FunctionDao functionDao;
	
	static {
		functionDao = OrgDaoManager.getOrgDaoFactory().getFunctionDao();
	}
	
	@Override
	public Function get(int id) {
		if(Function.ROOT_ID.equals(id)) {
			return Function.createRootFunction();
		} else {
			return functionDao.get(id);
		}
	}

	@Override
	public void save(Function function) {		
		function.setParentIdPath(getParentIdPath( function.getParentId())); 		
		functionDao.save(function);
	}
		
	@Override
	public int update(Function function) {
		return functionDao.update(function);
	}

	@Override
	public int setValidState(int id, ValidState validState) {
		return functionDao.setValidState(id, validState.value);
	}

	@Override
	public List<Function> findFunctions() {
		return functionDao.findFunctions();
	}

	private static String getParentIdPath(int funcId) {
		if(Function.ROOT_ID == funcId) {
			return Function.ROOT_ID + ",";
		} else {
			Function obj = functionDao.get(funcId);
			return String.format("%s%d,", obj.getParentIdPath(), obj.getId());
		}
	}

	@Override
	public List<Function> findChildren(int parentId) {
		return functionDao.findChildByParentId(parentId);
	}	
}
